<template>
  <div class="pd30 contract">
    <div class="panelWrap">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>按需维保合同管理</div>
      </div>
      <div class="con">
        <div class="con-row flex flexac pl search-box">
          <!-- <div class="flex flexac">
            <el-input v-model="param.id" class="co-input" placeholder="请输入电梯ID..." />
          </div> -->
          <div class="flex flexac">
            <el-input v-model="param.contractNumber" class="co-input" placeholder="请输入合同编号..." @input="getContList" />
          </div>
          <div class="groupbtn flex m-l-40 ">
            <el-button class="flex flexac m-r-20 fs14" size="small" type="warning" @click="getContList"><i class="co-i" /><span class="search1">查 询</span></el-button>
            <el-button class="co-empty flexcenter m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
          </div>
        </div>
        <div class="con-row flex flexac flexjcsb pl">
          <el-button class="defaultbtn" type="primary" @click="handleRefresh"><i class="el-icon-refresh" :class="refresh?'goRefresh':''" />刷 新</el-button>
          <div class="m-r-25 flex">
            <el-button class="defaultbtn" type="primary" @click="handleAdd"><i class="el-icon-circle-plus-outline" />添加</el-button>
            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
            <div class="pre m-l-10">
              <el-button class="defaultbtn pre" type="primary" @click="handleSenior('field')"><i class="iconfont icon-shezhi" />字段
              </el-button>
              <div class="selectUl" :class="seniorSet.field?'showSelectUl':'hideSelectUl'">
                <div v-for="(item,i) in tablehead" :key="i" class="li">
                  <el-checkbox v-model="item.isShow">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <div class="pre m-l-10">
              <el-button class="defaultbtn" type="primary" @click="handleSenior('sortable')"><i class="iconfont icon-shezhi" />排序</el-button>
              <div class="selectUl" :class="seniorSet.sortable?'showSelectUl':'hideSelectUl'">
                <div v-for="(item,i) in tablehead" v-if="item.isShow" :key="i" class="li">
                  <el-checkbox v-model="item.sortable">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <!-- <el-button class="defaultbtn" @click="handleExportExcel" type="primary"><i class="iconfont icon-shezhi"></i>固定</el-button> -->
          </div>
        </div>

        <el-table
          id="contList"
          ref="contList"
          class="con-table"
          type="expand"
          :data="contList"
          style="width: 100%"
          highlight-current-row
        >

          <template v-for="item in tablehead">
            <el-table-column v-if="item.isShow" :key="item.index" :width="item.width" align="center" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
          </template>

          <el-table-column align="center" label="合同有效期">
            <template slot-scope="scope">
              <span>{{ scope.row.startDate }} - {{ scope.row.endDate }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="基本操作">
            <template slot-scope="scope">
              <el-button class="defaultbtn" type="primary" plain size="mini" @click="handleEdit(scope.$index, scope.row)">
                <i class="el-icon-edit" />
                编辑</el-button>
              <!-- <el-button type="danger" class="defaultbtn" @click="handleDeleteBtn(scope.$index, scope.row)"><i class="el-icon-delete-solid" />删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="paginationWrap flex " :current-page="paging.currentPage" :page-sizes="paging.pageSizeArr" :page-size="paging.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <ContDialog v-model="contVisible" :data="contData" :is-edit="isEdit" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseDialog" />
  </div>
</template>

<script>

import ContDialog from './dialog/index'
import { miContQueryList, miContDelete, miContDetail } from '@/api/maintenance/contract'
import { showNotice, formatDateTime } from '@/utils/toolclass'
import { preImageView } from '@/api/maintenance/Filecontrller'
// import storage from '@/utils/storage'
import bus from '@/utils/bus'

export default {
  name: 'Contract',
  components: { ContDialog },
  props: {},
  data() {
    return {
      paging: {
        currentPage: 1,
        pageSize: 10,
        pageSizeArr: [10, 20, 50, 100],
        total: 0
      },

      contList: [],
      maintenanceUnit: [],
      param: {
        contractNumber: '',
        userUnitId: ''
      },
      contVisible: false,
      contData: {},
      isEdit: false,
      refresh: false,
      seniorSet: {
        'field': false,
        'sortable': false
      },
      tablehead: [
        {
          index: 0,
          prop: 'index',
          label: '序号',
          width: '80',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'maUnitName',
          label: '维保单位',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 2,
          prop: 'userUnitName',
          label: '使用单位',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 3,
          prop: 'contractNumbe',
          label: '合同编号',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 4,
          prop: 'method',
          label: '维保方式',
          sortable: false,
          fixed: true,
          isShow: true
        }
      ]
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getContList()
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/demand/contract' }))
  },
  methods: {
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
      }
      if (type === 'sortable') {
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },

    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['维保单位', '使用单位', '合同编号', '有效期']
        const filterVal = ['maUnitName', 'userUnitName', 'contractNumbe', 'startDate']
        const data = this.formatJson(filterVal, this.contList)
        export_json_to_excel(tHeader, data, '按需合同列表(' + formatDateTime().ymd) + ')'
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleRefresh() {
      this.refresh = true
      this.getContList()
      setTimeout(() => {
        this.refresh = false
      }, 1200)
    },
    getContList() {
      miContQueryList(this.param.contractNumber, this.paging.currentPage, this.paging.pageSize, this.param.userUnitId).then((res) => {
        // console.log(res)
        if (res.code === '000000') {
          var newArr = res.data.filter((item, i) => {
            if (item.method === 1) {
              // console.log(item)
              return item
            }
          })
          this.contList = newArr.map((item, i) => {
            this.items = {
              index: i > 0 ? i : (i + 1),
              contractNumbe: item.contractNumbe, // 合同编号
              crtDate: item.crtDate === '' ? '' : this.$moment(item.crtDate).format('YYYY-MM-DD'), // 创建时间
              crtOpr: item.crtOpr, // 创建人
              endDate: item.endDate === '' ? '' : this.$moment(item.endDate).format('YYYY-MM-DD'), // 结束时间
              filePath: item.filePath, // 合同文件路径
              id: item.id, // ID
              lstEdtDate: item.lstEdtDate === '' ? '' : this.$moment(item.lstEdtDate).format('YYYY-MM-DD'), // 最后修改时间
              lstEdtOpr: item.lstEdtOpr, // 最后修改人ID
              maUnitId: item.maUnitId, // 维保单位ID
              maUnitName: item.maUnitName, // 维保单位名称
              method: item.method === 1 ? '按需维保' : '强制维保', // 维保方式(1:按需维保，2：强制维保)
              orgId: item.orgId, // 机构id
              price: item.price, // 价格
              startDate: item.startDate === '' ? '' : this.$moment(item.startDate).format('YYYY-MM-DD'), // 开始时间
              userUnitId: item.userUnitId, // 使用单位ID
              userUnitName: item.userUnitName, // 使用单位名称
              version: item.version, // 版本号
              elecatorList: []
            }
            return this.items
          })
          this.paging = {
            currentPage: res.pager.pageIndex,
            pageSize: res.pager.pageSize,
            total: res.pager.totalSize
          }
        }
      })
    },
    handleEmptySearch() {
      this.param.contractNumber = ''
      this.param.userUnitId = ''
      this.getContList()
    },
    handleEdit(index, row) {
      miContDetail(row.id).then(res => {
        // console.log(res)
        bus.$emit('eles', res.data.elecatorList)
        // console.log(res.data.elecatorList)
      })
      this.contVisible = true
      this.isEdit = true
      // console.log(row)
      preImageView(row.filePath).then(res => {
        // console.log(res)
        return 'data:image/jpeg;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }).then(data => {
        // console.log(data)
        this.contData = {
          contractNumbe: row.contractNumbe, // 合同编号
          crtDate: row.crtDate, // 创建时间
          crtOpr: row.crtOpr, // 创建人
          endDate: row.endDate, // 结束时间
          filePath: data, // 合同文件路径
          fileImage: row.filePath,
          id: row.id, // ID
          lstEdtDate: row.lstEdtDate, // 最后修改时间
          lstEdtOpr: row.lstEdtOpr, // 最后修改人ID
          maUnitId: row.maUnitId, // 维保单位ID
          maUnitName: row.maUnitName, // 维保单位名称
          method: row.method === 1 ? '按需维保' : '强制维保', // 维保方式(1:按需维保，2：强制维保)
          orgId: row.orgId, // 机构id
          price: row.price, // 价格
          startDate: row.startDate, // 开始时间
          userUnitId: row.userUnitId, // 使用单位ID
          userUnitName: row.userUnitName, // 使用单位名称
          version: row.version, // 版本号
          elecatorList: row.elecatorList
        }
      })
    },
    handleAdd() {
      this.contVisible = true
      this.isEdit = false
      this.contData = {
        contractNumbe: '', // 合同编号
        crtDate: '', // 创建时间
        crtOpr: '', // 创建人
        endDate: '', // 结束时间
        filePath: '', // 合同文件路径
        id: 0, // ID
        lstEdtDate: '', // 最后修改时间
        lstEdtOpr: '', // 最后修改人ID
        maUnitId: '', // 维保单位ID
        maUnitName: '', // 维保单位名称
        method: '按需维保', // 维保方式(1:按需维保，2：强制维保)
        orgId: '', // 机构id
        price: '888888', // 价格
        startDate: '', // 开始时间
        userUnitId: '', // 使用单位ID
        userUnitName: '', // 使用单位名称
        version: '' // 版本号
      }
    },
    handleDeleteBtn(index, row) {
      this.$alert('这个操作会删除和它相关联的所有数据,确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleDelete(row.id)
          }
        }
      })
    },
    handleDelete(id) {
      miContDelete(id).then((res) => {
        if (res.code === '000000') {
          showNotice('success', '提示', '删除成功')
          this.getContList()
        } else {
          // showNotice('error', '提示', res.msg)
        }
      })
    },
    handleCloseDialog() {
      this.contVisible = !this.contVisible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
      this.getContList()
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
      this.getContList()
    }
  }
}
</script>

<style scoped lang="scss">
.contract {
  .con-img {
    width: 60px;
    height: 40px;
    border-radius: 4px;;
  }
}
</style>
